package com.example.mymnue;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ShopActivity extends AppCompatActivity implements Runnable, View.OnClickListener , AdapterView.OnItemLongClickListener {
    private static final String TAG = "AA";
    private ShopDB db;
    private SimpleAdapter simpleAdapter;
    private List<HashMap<String, Object>> listItems; // 存放文字、图片信息
    private HashMap<String, Object> map;
    private Handler handler1;
    private List<CaidanItem> caidanItemList;
    private CaidanDBManager cd;
    private Button btn;
    private static String s="http://172.22.160.1:8084/menu/MenuServlet";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        ListView slist = findViewById(R.id.slist);
        initListView();
        slist.setAdapter(simpleAdapter);
        Thread thread = new Thread(this);
        thread.start();
        handler1 = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 7) {
                    listItems = (List<HashMap<String, Object>>) msg.obj;
                    simpleAdapter = new SimpleAdapter(ShopActivity.this, listItems,
                            R.layout.list_item_shop,
                            new String[]{"title", "detail"},
                            new int[]{R.id.textView13, R.id.textView14});
                    slist.setAdapter(simpleAdapter);
                }
                super.handleMessage(msg);
            }
        };
        btn = findViewById(R.id.button2);
        btn.setOnClickListener(this);
        slist.setOnItemLongClickListener(this);
    }

    private void initListView() {
        listItems = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < 10; i++) {
            map = new HashMap<String, Object>();
            map.put("title", i);
            map.put("detail", i); // 详情描述
            listItems.add(map);
        }
        // 生成适配器的Item和动态数组对应的元素
        simpleAdapter = new SimpleAdapter(this, listItems, // listItems数据源
                R.layout.list_item_shop, // ListItem的XML布局实现
                new String[]{"title", "detail"},
                new int[]{R.id.textView13, R.id.textView14}
        );
    }

    @Override
    public void run() {
        db = new ShopDB(this, "mymenu.db", null, 1);
        listItems = new ArrayList<HashMap<String, Object>>();
        SQLiteDatabase sd = db.getWritableDatabase();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        cd = new CaidanDBManager(this);
        caidanItemList = cd.list();
        Log.i(TAG, "run: caidan  " + caidanItemList + "=" + caidanItemList.size());
        for (int i = 0; i < caidanItemList.size(); i++) {
            if (caidanItemList.get(i).getDdata().equals(curDateStr)) {
                map = new HashMap<String, Object>();
                map.put("title", caidanItemList.get(i).getDtitle());
                map.put("detail", caidanItemList.get(i).getDdtail());
                listItems.add(map);
            }
        }
        Message msg = new Message();
        msg.what = 7;
        msg.obj = listItems;
        handler1.sendMessage(msg);
    }


    @Override
    public void onClick(View v) {
        new Thread(){
            public void run(){
                try {
                    URL url=new URL(s);
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    OutputStream out=conn.getOutputStream();
                    String ss=listItems.get(0).get("title").toString();
                    Log.i(TAG, "run: ss="+ss);
                    out.write(ss.getBytes());
                    conn.getInputStream();
                    out.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.backmenu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.back:
                Intent intent1 = new Intent(ShopActivity.this, MainActivity.class);
                startActivity(intent1);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG, "onItemLongClick: position ="+position);
        AlertDialog.Builder del=new AlertDialog.Builder(this);
        del.setTitle("提示")
                .setMessage("请确认是否删除此菜品")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(TAG, "onClick: listitem="+listItems);
                        listItems.remove(listItems.get(position));
                        simpleAdapter.notifyDataSetChanged();
                    }
                }).setNegativeButton("否",null);
        del.create().show();
        return true;
    }
}